<template>
  <div class="app-container">
    <!-- 上部分表单 -->
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="85px" class="globalSerchFormStyle"
      :rules="rules">
      <el-row>
        <el-col :span="6" v-if="authUser">
          <el-form-item label="油企名称" size="small">
            <el-select style="width: 180px" v-model="queryParams.enterpriseId" :clearable="true" filterable
              placeholder="请选择油企" @change="handleSelectChange">
              <el-option v-for="item in enterpriseList" :value="item.enterpriseId"
                :label="item.enterpriseName"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6" v-if="[null, '', '1', '7'].includes($store.state.user.userLevel)">
          <el-form-item label="油站名称" size="small">
            <el-select style="width: 180px" v-model="queryParams.stationId" :clearable="true" filterable
              placeholder="请选择油站名称">
              <el-option v-for="item in stationList" :key="item.stationId" :label="item.stationName"
                :value="item.stationId">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="活动名称">
            <el-input style="width: 180px" v-model.trim="queryParams.activityName" placeholder="请输入活动名称" clearable
              @keyup.enter.native="handleQuery" size="small" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="活动状态" size="small">
            <el-select style="width: 180px" v-model="queryParams.activityStatus" placeholder="请选择活动状态" clearable>
              <el-option v-for="item in activityStatus" :value="item.value" :label="item.label"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-row class="global_el_rowStyle" :gutter="10" style="
        border-top: none;
        border-bottom: 1px solid #f5f5f5;
        margin-top: 0px;
      ">
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-search" @click="handleQuery" size="mini">搜索</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" @click="resetQuery" size="mini" icon="el-icon-refresh" plain>重置</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-plus" @click="handleAdd" size="mini">新增</el-button>
      </el-col>
    </el-row>

    <el-table stripe style="width: 100%" :data="dataList" ref="tableRef" v-loading="loading" border>
      <af-table-column align="center" width="200" label="活动名称" show-overflow-tooltip prop="activityName" />
      <af-table-column align="center" width="300" label="活动时间">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startDate, "{y}-{m}-{d} {h}:{i}:{s}") }}至{{
            parseTime(scope.row.endDate, "{y}-{m}-{d} {h}:{i}:{s}")
          }}</span>
        </template>
      </af-table-column>
      <af-table-column align="center" v-if="authUser" width="200" label="归属油企" prop="enterpriseName" />
      <af-table-column align="center" v-if="[null, '', '1', '7'].includes($store.state.user.userLevel)" label="归属油站" prop="stationName"
        width="200" />
      <af-table-column align="center" width="200" label="活动状态" prop="activityStatus">
        <template slot-scope="scope">
          <span>{{
            scope.row.activityStatus === "run" ? "进行中" : "已停止"
            }}</span>
        </template>
      </af-table-column>
      <af-table-column align="center" width="200" label="活动启停" prop="status">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.status" active-value="0" inactive-value="1"
            @change="changeStatus($event, scope.row)">
          </el-switch>
        </template>
      </af-table-column>
      <af-table-column align="center" label="操作">
        <template slot-scope="scope">
          <el-button type="text" @click="handleView(scope.row)">
            查看
          </el-button>
          <el-button type="text" :disabled="scope.row.activityStatus === 'run'" @click="handleEdit(scope.row)">
            编辑
          </el-button>
          <el-button type="text" @click="handleDel(scope.row)">
            删除
          </el-button>
        </template>
      </af-table-column>
    </el-table>

    <!-- 积分活动 新增 查看 编辑弹窗 -->
    <el-drawer title="新建积分抵现活动" size="50%" :before-close="handleCancel" :visible.sync="dialog" ref="drawer">
      <div class="drawer_content">
        <el-form :model="activeForm" :rules="rules" ref="activeFormRef">
          <el-row>
            <el-form-item label="活动名称" prop="activityName">
              <el-input v-model="activeForm.activityName" placeholder="请选择活动名称" style="width: 300px"
                :disabled="type === 'view'"></el-input>
            </el-form-item>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="归属油企" prop="enterpriseId" v-if="authUser">
                <el-select v-model="activeForm.enterpriseId" placeholder="请选择油企" style="width: 300px"
                  :disabled="type === 'view'">
                  <el-option v-for="item in enterpriseList" :value="item.enterpriseId"
                    :label="item.enterpriseName"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="归属油站" prop="stationId">
                <el-select v-model="activeForm.stationId" placeholder="请选择油站" style="width: 300px"
                  :disabled="type === 'view'">
                  <el-option v-for="item in stationList" :label="item.stationName" :value="item.stationId" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-form-item label="活动时间" prop="createDate" size="small">
              <el-date-picker size="small" v-model="dateRangeCreatedDate" value-format="yyyy-MM-dd HH:mm:ss"
                type="datetimerange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"
                style="width: 300px" :disabled="type === 'view'">
              </el-date-picker>
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item label="规则设置" prop="ruleSet">
              <el-card class="box-card">
                <div class="card_main">
                  <div>金额抵扣</div>
                  <div>
                    每&nbsp;<el-input v-model="activeForm.integralDeductionRuleList[0].integralNum
                      " style="width: 100px" size="mini" :disabled="type === 'view'" />
                    &nbsp;积分抵现&nbsp;
                    <el-input v-model="activeForm.integralDeductionRuleList[0].amt" style="width: 100px" size="mini"
                      :disabled="type === 'view'" />&nbsp;元
                  </div>
                </div>
                <div class="card_main">
                  <div>抵扣限制</div>
                  <el-radio-group v-model="activeForm.integralDeductionRuleList[0].ruleType" size="mini"
                    :disabled="type === 'view'">
                    <el-radio label="1">不限制</el-radio>
                    <el-radio label="2">固定限制</el-radio>
                    <el-radio label="3">梯度限制</el-radio>
                  </el-radio-group>
                </div>
                <div v-if="
                  activeForm.integralDeductionRuleList[0].ruleType === '2'
                ">
                  <div class="flex_box">
                    <el-card class="card_sub">
                      <div>
                        最大允许抵扣额度&nbsp;
                        <el-input v-model="activeForm.integralDeductionRuleList[0]
                            .gradientRuleList[0].maxAmt
                          " style="width: 100px" size="mini" :disabled="type === 'view'" />&nbsp;元
                      </div>
                    </el-card>
                  </div>
                </div>
                <div v-if="
                  activeForm.integralDeductionRuleList[0].ruleType === '3'
                ">
                  <div v-for="(ele, index) in activeForm
                    .integralDeductionRuleList[0].gradientRuleList" :key="ele.activityId" class="flex_box">
                    <el-card class="card_sub">
                      <div>
                        实付&nbsp;<el-input v-model="ele.amt" style="width: 100px" size="mini"
                          :disabled="type === 'view'" />
                        &nbsp;元，最大抵扣&nbsp;
                        <el-input v-model="ele.maxAmt" style="width: 100px" size="mini"
                          :disabled="type === 'view'" />&nbsp;元
                      </div>
                    </el-card>
                    <div class="card_btn">
                      <i @click="goAdd(index)" class="iconfont icon-jia" circle></i>
                      <i @click="goDel(index, ele.id)" class="iconfont icon-jianshao" v-show="activeForm.integralDeductionRuleList[0]
                          .gradientRuleList.length > 1
                        "></i>
                    </div>
                  </div>
                </div>
              </el-card>
            </el-form-item>
          </el-row>
          <div class="footer">
            <el-button type="primary" @click="handleSubmit" :loading="dialogLoading"
              :disabled="type === 'view'">确定</el-button>
            <el-button @click="handleCancel">取 消</el-button>
          </div>
        </el-form>
      </div>
    </el-drawer>

    <!-- 分页 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />
  </div>
</template>
<script>
import { enterpriseList } from "@/api/station/order";
import { listEnterpriseStation, getStationByEnterprise } from "@/api/dept";
import getUserProfileName from "@/utils/getUserProfile";
import {
  deductDel,
  getDeduction,
  getDeductList,
  saveDeduction,
  updateDeduction,
  delRule,
} from "@/api/customer/cashActivity";

import { cloneDeep } from "lodash";
import { mapState } from "vuex";
export default {
  name: "Cash_Activity",
  data() {
    const createDateValidator = (value, rule, callback) => {
      if (this.dateRangeCreatedDate.length > 0) {
        return callback();
      } else {
        return callback(new Error("请选择活动时间"));
      }
    };
    const ruleSetValidator = (value, rule, callback) => {
      const obj = this.activeForm.integralDeductionRuleList[0];
      const obj2 = obj.gradientRuleList[0];
      const { ruleType, amt, integralNum } = obj
      if (ruleType === "1" && integralNum && amt) {
        return callback();
      } else if (ruleType === "2" && obj2.maxAmt) {
        return callback();
      } else if(obj2.amt && obj2.maxAmt){
        return callback();
      } else {
        return callback(new Error("请输入活动金额"));
      }
    };
    return {
      activityStatus: [
        { value: "run", label: "进行中" },
        { value: "stop", label: "已停止" },
      ],
      dataList: [],
      // 总条数
      total: 0,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        activityName: "",
        activityStatus: "",
      },
      stationList: [],
      enterpriseList: [],
      loading: false,
      dialogLoading: false,
      dialog: false,
      activeForm: {
        enterpriseId: "",
        stationId: "",
        activityName: "",
        integralDeductionRuleList: [
          {
            amt: "",
            gradientRuleList: [
              {
                amt: "",
                maxAmt: "",
                isDeleted: 0,
              },
            ],
            integralNum: "",
            ruleType: "1",
          },
        ],
      },
      rules: {
        createDate: [
          { required: true, validator: createDateValidator, trigger: "change" },
        ],
        enterpriseId: [
          { required: true, message: "请选择归属油企", trigger: "change" },
        ],
        stationId: [
          { required: true, message: "请选择归属油站", trigger: "change" },
        ],
        activityName: [
          { required: true, message: "请输入活动名称", trigger: "change" },
        ],
        ruleSet: [
          { required: true, validator: ruleSetValidator, trigger: "change" },
        ],
      },
      dateRangeCreatedDate: [],
      type: "add",
    };
  },
  async created() {
    this.getList();
    this.getEnterpriseList();
    // 如果当前是油企账号，则获取该企业下的油站
    if (this.presentEnterprise && this.presentEnterprise.enterpriseId) {
      this.getStationList(this.presentEnterprise.enterpriseId);
    } else {
      this.getStationList();
    }
  },
  methods: {
    async changeStatus(e, row) {
      const res = await updateDeduction({
        activityId: row.activityId,
        status: e,
      });
      this.getList();
      this.$message.success(res.msg);
    },
    goAdd(index) {
      const arr = this.activeForm.integralDeductionRuleList[0].gradientRuleList;
      arr.splice(index+1, 0, { amt: "", maxAmt: "" });
    },
    async goDel(index, id) {
      const arr = this.activeForm.integralDeductionRuleList[0].gradientRuleList;
      arr.splice(index, 1);
      if (this.type === "edit" && id) {

        const res = await delRule({ id });
      }
    },
    async handleSubmit() {
      await this.$refs.activeFormRef.validate();
      const startDate = this.dateRangeCreatedDate[0];
      const endDate = this.dateRangeCreatedDate[1];
      let data = { ...cloneDeep(this.activeForm), startDate, endDate };

      data.enterpriseId =
        data.enterpriseId ||
        this.$store.state.user.presentEnterprise.enterpriseId;
      console.log(data);
      if (data.integralDeductionRuleList[0].ruleType === "1") {
        data.integralDeductionRuleList[0].gradientRuleList = null;
      }
      this.dialogLoading = true;
      let res;
      try {
        if (this.type === "add") {
          res = await saveDeduction(data);
        } else {
          res = await updateDeduction(data);
        }
        this.$message.success(res.msg);
      } finally {
        this.dialogLoading = false;
      }
      this.dialog = false;
      this.getList();
    },
    handleCancel() {
      this.dialog = false;
      this.activeForm = {
        enterpriseId: "",
        stationId: "",
        activityName: "",
        integralDeductionRuleList: [
          {
            amt: "",
            gradientRuleList: [
              {
                amt: "",
                maxAmt: "",
              },
            ],
            integralNum: "",
            ruleType: "1",
          },
        ],
      };
      this.$refs.activeFormRef.resetFields();
      this.dateRangeCreatedDate = []
    },
    handleView(row) {
      this.handleViewOrEdit(row, "view");
    },
    handleEdit(row) {
      this.handleViewOrEdit(row, "edit");
    },
    async handleViewOrEdit(row, type) {
      this.type = type;
      this.dialog = true;
      const res = await getDeduction({ activityId: row.activityId });
      this.activeForm = res.data;
      this.dateRangeCreatedDate = [res.data.startDate, res.data.endDate];
    },
    async handleDel(row) {
      await this.$confirm(`是否删除${row.activityName}活动？`, "提醒", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      });
      const res = await deductDel({ activityId: row.activityId });
      this.getList();
      this.$message.success(res.msg);
    },
    // 根据油企获取油站
    handleSelectChange(value) {
      this.stationList = [];
      this.queryParams.stationId = null;
      this.getStationList(value);
    },
    // 查询油企
    getEnterpriseList() {
      enterpriseList().then((res) => {
        this.enterpriseList = res.rows;
      });
    },

    /** 查询订单支付列表 */
    async getList() {
      this.loading = true;
      let queryParams = cloneDeep(this.queryParams);
      // 列表请求
      try {
        const res = await getDeductList(queryParams);
        this.dataList = res.rows;
        this.total = res.total;
      } finally {
        this.loading = false;
      }
    },

    async getStationList(val) {
      // 判断是不是admin账号
      const isDelete = await getUserProfileName();
      if (isDelete && val) {
        // 是
        listEnterpriseStation({ enterpriseId: val }).then((res) => {
          this.stationList = res;
        });
      } else {
        // 不是
        const res = await getStationByEnterprise();
        this.stationList = res.data;
      }
    },

    /** 搜索按钮操作 */
   handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    /** 重置按钮操作 */
    resetQuery() {
      // this.dateRangeCreatedDate = [];
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        activityName: "",
        activityStatus: "",
      };
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleAdd() {
      this.$refs.activeFormRef && this.$refs.activeFormRef.resetFields()
      this.type = "add";
      this.dialog = true;
    },
  },
  computed: {
    ...mapState({
      userLevel: (state) => state.user.userLevel,
    }),
    authUser() {
      let roles = this.$store.state.user.roles;
      if (roles.includes("admin") || roles.includes("1000")) {
        return true;
      } else {
        return false;
      }
    },
  },
};
</script>
<style lang="scss" scoped>
.app-container {
  margin-top: -15px;
}

.box-card {
  width: 70%;
  // height: 200px;
}

.drawer_content {
  padding: 20px;
  height: 90vh;
  overflow-y: auto;

  ::v-deep .el-form-item__label {
    width: 100%;
    text-align: left;
  }

  ::v-deep .el-radio-group {
    font-size: 1em;
    line-height: inherit;
  }

  .card_main {
    line-height: 60px;
    display: flex;
    align-items: center;
  }

  .card_main>div:first-child {
    margin-right: 20px;
  }

  .card_sub {
    height: 50px;
    width: 70%;
    margin-left: 13%;
    margin-bottom: 10px;

    ::v-deep .el-card__body {
      padding: 5px 20px;
    }
  }

  .flex_box {
    display: flex;
    align-items: center;
  }

  .card_btn {
    display: flex;
    align-items: center;
    width: 64px;
    margin-left: 10px;
    justify-content: space-between;
  }

  .footer {
    text-align: right;
  }
}

.amt_sty {
  ::v-deep .el-input__inner {
    width: 95%;
  }
}

::v-deep .card-table {
  padding: 10px;
  margin-top: 8px;
  background-color: #f8f8f8;

  .el-button {
    margin: 0 5px 0 0;
  }
}

::v-deep .el-table {
  border: 1px #f8f8f8 solid;
  border-bottom: 1px #dfe6ec solid;
}

::v-deep .is-center {
  border: 1px transparent solid;
  border-bottom: 1px #f8f8f8 solid;
}

.order-fz {
  font-size: 13px;
}

.order-text-color {
  color: #1990ff;
}

@font-face {
  font-family: "iconfont";
  /* Project id 4526146 */
  src: url("//at.alicdn.com/t/c/font_4526146_u4rmavflj4.woff2?t=1714116710523") format("woff2"),
    url("//at.alicdn.com/t/c/font_4526146_u4rmavflj4.woff?t=1714116710523") format("woff"),
    url("//at.alicdn.com/t/c/font_4526146_u4rmavflj4.ttf?t=1714116710523") format("truetype");
}

.iconfont {
  font-family: "iconfont" !important;
  font-size: 16px;
  font-style: normal;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

.icon-jia:before {
  content: "\e600";
  color: #1296db;
  font-size: 28px;
}

.icon-jianshao:before {
  color: #d81e06;
  content: "\e8c5";
  font-size: 28px;
}
</style>
